<script setup>
import { Icon } from '@iconify/vue';
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus'
import axios from 'axios';

const loading1 = ref(false)

//地区名字汇总
const names = ref([]);

const chartContainer1 = ref(null);

//定义数据模型
const RegionData = ref({
    name: '东城区',
    loadName: '商业区',
    data: '2025-01-01',
    temperature: '20',
})
const regiondata = ref({
    name: '',
    loadName: '',
    data: '',
    temperature: '',
});

const fire = Array(24).fill(100);
const water = Array(24).fill(200);
const wind = Array(24).fill(300);
const solar = Array(24).fill(400);
const nuclear = Array(24).fill(500);

// 初始化 ECharts 图表实例
let chartInstance1 = null; // 折线图实例

// 初始曲线图逻辑
const initChart1 = () => {
    if (chartContainer1.value) {
        chartInstance1 = echarts.init(chartContainer1.value);

        const option = {
            title: {
                text: '电力来源24h曲线图'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['火力发电', '水力发电', '风力发电', '太阳能发电', '核能发电']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: ['00:00', '00:01', '00:02', '00:03', '00:04', '00:05',
                    '00:06', '00:07', '00:08', '00:09', '00:10', '00:11',
                    '00:12', '00:13', '00:14', '00:15', '00:16', '00:17',
                    '00:18', '00:19', '00:20', '00:21', '00:22', '00:23']
            },
            yAxis: {
                type: 'value',
            },
            series: [
                {
                    name: '火力发电',
                    type: 'line',
                    data: fire,
                    smooth: true
                },
                {
                    name: '水力发电',
                    type: 'line',
                    data: water,
                    smooth: true
                },
                {
                    name: '风力发电',
                    type: 'line',
                    data: wind,
                    smooth: true
                },
                {
                    name: '太阳能发电',
                    type: 'line',
                    data: solar,
                    smooth: true
                },
                {
                    name: '核能发电',
                    type: 'line',
                    data: nuclear,
                    smooth: true
                }
            ]
        };

        chartInstance1.setOption(option);
    }
};

import { FindAllNameService } from '@/api/electric.js'

// 重置按钮
const reback = () => {

    if (loading1.value) {
        ElMessage.error("正在预测中,请稍等...");
        return;
    }

    RegionData.value.name = '东城区';
    RegionData.value.loadName = '商业区';
    RegionData.value.data = '2025-01-01';
    RegionData.value.temperature = '20';
};

//获取所有地区列表 
const List = async () => {
    try {
        let result = await FindAllNameService();
        if (!result || !Array.isArray(result)) {
            throw new Error('Invalid data format from API');
        }
        names.value = result;
    } catch (error) {
        console.error('Error fetching names:', error);
        ElMessage.error('无法加载地区分类，请稍后重试');
    }
};

function getDayOfWeek(dateString) {
    const baseDate = new Date('2025-01-01'); // 基准日期是周三
    const targetDate = new Date(dateString);

    // 计算天数差
    const diffTime = targetDate.getTime() - baseDate.getTime();
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

    // 2025-01-01 是周三 => 基础值为 3
    const baseWeekDay = 3;

    // 计算新的星期数（以周一为1，周日为7）
    let weekDay = (baseWeekDay + diffDays) % 7;
    if (weekDay <= 0) weekDay += 7;

    return weekDay;
}


const search = async () => {

    if (loading1.value) {
        ElMessage.error("正在预测中,请稍等...");
        return;
    }

    loading1.value = true;
    // 检查name data 是否为空
    if (!RegionData.value.name || !RegionData.value.loadName || !RegionData.value.data || !RegionData.value.temperature) {
        ElMessage.warning('请填写数据完整！');
        return;
    }

    regiondata.value.temperature = RegionData.value.temperature;
    regiondata.value.name = RegionData.value.name;

    // 格式化子区分类的输出
    switch (RegionData.value.loadName) {
        case '商业区':
            regiondata.value.loadName = 1;
            break;
        case '工业区':
            regiondata.value.loadName = 2;
            break;
        case '居民区':
            regiondata.value.loadName = 3;
            break;
        case '行政区':
            regiondata.value.loadName = 4;
            break;
    }

    // 使用本地时间格式化日期，避免 toISOString 的时区偏移
    const selectedDate = new Date(RegionData.value.data);
    const year = selectedDate.getFullYear();
    const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
    const day = String(selectedDate.getDate()).padStart(2, '0');
    RegionData.value.data = `${year}-${month}-${day}`;

    if (year !== 2025) {
        ElMessage.warning('请选择2025年的日期!');
        return;
    }

    regiondata.value.data = RegionData.value.data;

    console.log(regiondata.value)

    let fire1 = Array(24).fill(100);
    let water1 = Array(24).fill(200);
    let wind1 = Array(24).fill(300);
    let solar1 = Array(24).fill(400);
    let nuclear1 = Array(24).fill(500);

    try {
        const week = getDayOfWeek(regiondata.value.data);
        console.log("gogogo")
        for (let resource = 1; resource <= 5; resource++) {

            switch (resource) {
                case 1: ElMessage.success('正在预测火力发电，请稍等...'); break;
                case 2: ElMessage.success('正在预测水力发电，请稍等...'); break;
                case 3: ElMessage.success('正在预测风力发电，请稍等...'); break;
                case 4: ElMessage.success('正在预测太阳能发电，请稍等...'); break;
                case 5: ElMessage.success('正在预测核能发电，请稍等...'); break;
            }

            for (let hour = 0; hour < 24; hour++) {
                const payload = {
                    region_name: regiondata.value.name,
                    record_hour: hour,
                    day_of_week: week,
                    temperature: Number(regiondata.value.temperature),
                    load_name: regiondata.value.loadName,
                    resource: resource
                };

                const result = await axios.post('http://localhost:500/predict', [payload], {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                const value = result.data.predictions[0]; // 取第一个预测值
                switch (resource) {
                    case 1: fire1[hour] = value.toFixed(2); break;
                    case 2: water1[hour] = value.toFixed(2); break;
                    case 3: wind1[hour] = value.toFixed(2); break;
                    case 4: solar1[hour] = value.toFixed(2); break;
                    case 5: nuclear1[hour] = value.toFixed(2); break;
                }
            }
        }

        ElMessage.success('预测成功！');
        loading1.value = false;

        // 更新图表数据
        chartInstance1.setOption({
            series: [
                { data: fire1 },
                { data: water1 },
                { data: wind1 },
                { data: solar1 },
                { data: nuclear1 }
            ]
        });
    } catch (error) {
        ElMessage.error('查询失败，请稍后重试');
    }
}

// 窗口大小调整时重绘图表
const resizeCharts = () => {
    if (chartInstance1) {
        chartInstance1.resize();
    }
};

// 使用生命周期钩子
onMounted(async () => {
    await List();
    initChart1();
    window.addEventListener('resize', resizeCharts);
});
</script>

<template>
    <el-card>
        <template #header>
            <div class="header">
                <Icon icon="noto:chart-increasing" width="38" height="38" />
                <span style="font-size: 28px;"><strong>&nbsp;预测分析</strong></span>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form :model="RegionData" inline>
            <div>
                <el-form-item label="地区分类：">
                    <el-select placeholder="请选择地区" v-model="RegionData.name">
                        <el-option v-for="c in names" :key="c.regionName" :label="c.regionName" :value="c.regionName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="子区分类：">
                    <el-select placeholder="请选择子区" v-model="RegionData.loadName">
                        <el-option label="商业区" value="商业区"></el-option>
                        <el-option label="工业区" value="工业区"></el-option>
                        <el-option label="居民区" value="居民区"></el-option>
                        <el-option label="行政区" value="行政区"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="输入温度：">
                    <el-input v-model="RegionData.temperature" placeholder="请输入温度"></el-input>
                </el-form-item>

                <el-form-item label="选择日期：">
                    <el-date-picker v-model="RegionData.data" type="date" :size="size" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button @click="reback">重置</el-button>
                </el-form-item>
            </div>

            <el-card shadow="hover">
                <div v-loading="loading1" element-loading-text="正在预测,请稍等...">
                    <!-- 折线图 -->
                    <div ref="chartContainer1" style="width: 100%; height: 400px; margin-bottom: 20px;"></div>
                </div>
            </el-card>
        </el-form>
    </el-card>
</template>

<style lang="scss" scoped>
.search {
    display: flex;
}

.main-content {
    display: flex;
    margin-top: 20px;
}

.card-column {
    display: flex;
    flex-direction: column;
    gap: 38px;
    /* 控制上下间距 */
    width: 260px;
    margin-right: 20px;
    /* 卡片和图表间距 */
}

.info-card {
    height: 200px;
}

.chart-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.chart {
    width: 100%;
    height: 400px;
}


.main-content {
    display: flex;
    margin-top: 20px;
}

.el-select {
    width: 150px;
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}

.primary {
    margin-top: 100px;
}
</style>
